package epoch.game.core.server;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import epoch.game.core.config.ServerConfig;

public abstract class Server {
	private String server_name;

	public int server_id;
	private String agentName;
	protected ServerConfig serverConfig;
	public static final String DEFAULT_MAIN_THREAD = "Main";
	private static final Logger log = LogManager.getLogger(CloseByExit.class);

	protected Server(ServerConfig config) {
		this.serverConfig = config;
		if (this.serverConfig != null) {
			init();
		}
	}

	protected void init() {
		server_name = serverConfig.getName();
		if (((server_name == null) || ("".equals(server_name))) && (this.serverConfig.getName() != null) && (!"".equals(this.serverConfig.getName()))) {
			server_name = this.serverConfig.getName();
		}
		if ((server_id <= 0) && (this.serverConfig.getServerId() > 0)) {
			server_id = this.serverConfig.getServerId();
		}
		if (((agentName == null) || ("".equals(agentName))) && (this.serverConfig.getAgentName() != null) && (!"".equals(this.serverConfig.getAgentName()))) {
			agentName = this.serverConfig.getAgentName();
		}
		
	}

	public void start() {
		Runtime.getRuntime().addShutdownHook(new Thread(new CloseByExit(server_name), "ShutdownHook"));
	}

	public String getServerName() {
		return server_name;
	}

	public int getServerId() {
		return server_id;
	}

	public String getAgentName() {
		return agentName;
	}

	public ServerConfig getServerConfig() {
		return this.serverConfig;
	}
	
	protected abstract void stop();

	private class CloseByExit implements Runnable {
		private String server_name;

		public CloseByExit(String serverName) {
			this.server_name = serverName;
		}

		public void run() {
			Server.this.stop();
			Server.log.info(this.server_name + " Stop!");
		}
	}
}
